<script setup>
import { ref, onMounted } from 'vue'
import { queryItemAll, addItemDate, queryItemById, updateItemDate } from '@/api/item'
import { queryCategoryAll } from '@/api/category'
import { getSupplierAllList } from '@/api/supplier'
import { getAllBrands } from '@/api/brand'
import { ElMessage, ElMessageBox } from 'element-plus'
// 导入富文本框
import { QuillEditor } from '@vueup/vue-quill'
import '@vueup/vue-quill/dist/vue-quill.snow.css'

// 品牌下拉数据
const brandOptions = ref([])
// 获取品牌列表
const getBrands = async () => {
  try {
    const result = await getAllBrands()
    brandOptions.value = result?.data.map(brand => ({
      label: brand.name, 
      value: brand.id    
    })) || []
  } catch (error) {
    ElMessage.error('获取品牌列表失败')
  }
}

// 供应商的数据
const supplierData = ref([])
const supplierAllList = async () => {
  const result = await getSupplierAllList()
  supplierData.value = result.data
}

// 分类数据
const categoryData = ref([])
const getCategory = async () => {
  const result = await queryCategoryAll()
  categoryData.value = result.data
}
const props = { value: 'id', label: 'name', children: 'children' }

// 条件分页
const queryItem = async () => {
  const result = await queryItemAll(page.value, pageSize.value, itemDate.value.name, itemDate.value.code, itemDate.value.category)
  console.log(result.data);
  tableData.value = result.data.list
  total.value = result.data.total
}

// 清空数据
const clear = () => {
  itemDate.value = { name: '', code: '', category: '' }
  queryItem()
}

// 定义表单数据
const itemDate = ref({ name: '', code: '', category: '' })
// 定义表格数据
const tableData = ref([])
// 定义分页的变量
const page = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 分页事件
const handleSizeChange = (val) => {
  pageSize.value = val
  queryItem()
}
const handleCurrentChange = (val) => {
  page.value = val
  queryItem()
}

// 数据预加载
onMounted(() => {
  supplierAllList()
  queryItem()
  getCategory()
  getBrands()
})

// 弹出框相关
const title = ref(null)
const dialogShow = ref(false)
const dialogData = ref({
  id: '',
  code: '',
  title: '',
  categoryId: [],
  description: '',
  supplierId: '',
  brandId: '', 
  skuList: []
})

// 添加SKU
const addSkuList = () => {
  dialogData.value.skuList.push({
    skutitle: '',
    unit: '',
    skucode: '',
    productWeight: Number(sku.productWeight),
    productLength: Number(sku.productLength),
    productWidth: '',
    productHeight: '',
    productVolume: '',
    price: '',
    realPrice: ''
  })
}

// 删除SKU
const deleteSkuList = (index) => {
  dialogData.value.skuList.splice(index, 1)
}

// 打开添加弹窗
const saveItem = () => {
  title.value = '添加商品'
  dialogShow.value = true
  // 重置表单
  if (ruleFormRef.value) {
    ruleFormRef.value.resetFields()
  }
  // 清空表单数据
  dialogData.value = {
    id: '',
    code: '',
    title: '',
    categoryId: [],
    description: '',
    supplierId: '',
    brandId: '', 
    skuList: []
  }
}

// 保存商品信息
const saveItemInfo = async () => {
  if (!ruleFormRef.value) return
  await ruleFormRef.value.validate(async (valid) => {
    if (valid) {
      let result = null
      if (dialogData.value.id) {
        // 修改商品
        result = await updateItemDate(dialogData.value)
      } else {
        // 新增商品
        result = await addItemDate(dialogData.value)
      }
      if (result.code === 200) { 
        dialogShow.value = false
        queryItem()
        ElMessage.success('操作成功！')
      } else {
        ElMessage.error('操作失败！请重新操作')
      }
    }
  })
}

// 编辑商品（回显数据）
const getItemById = async (id) => {
  dialogShow.value = true
  const result = await queryItemById(id)
  title.value = '编辑商品信息'
  // 回显品牌ID
  dialogData.value = {
    ...result.data,
    brandId: result.data.brandId 
  }
  // 重置表单校验
  if (ruleFormRef.value) {
    ruleFormRef.value.resetFields()
  }
}

// 表单校验
const ruleFormRef = ref(null)
const rules = ref({
  code: [
    { required: true, message: '请输入商品编号', trigger: 'blur' },
    { min: 2, max: 50, message: '商品编号长度应在2到50个字符之间', trigger: 'blur' }
  ],
  title: [
    { required: true, message: '请输入商品名称', trigger: 'blur' },
    { min: 2, max: 20, message: '商品名称长度应在2到20个字符之间', trigger: 'blur' }
  ],
  brandId: [ // 校验品牌ID
    { required: true, message: '请选择品牌', trigger: 'change' }
  ]
})

// 表单标签宽度
const formLabelWidth = '120px'
</script>

<template>
  <div>
    <h3>商品管理</h3>
  </div>

  <!-- 搜索表单 -->
  <div>
    <el-form :inline="true" :model="itemDate" class="demo-form-inline">
      <el-form-item>
        <el-button type="primary" @click="saveItem">
          新增
        </el-button>
      </el-form-item>
      <el-form-item label="商品名称">
        <el-input v-model="itemDate.name" placeholder="请输入名称" />
      </el-form-item>
      <el-form-item label="商品编号">
        <el-input v-model="itemDate.code" placeholder="请输入编号" />
      </el-form-item>
      <el-form-item label="商品类别">
        <el-input v-model="itemDate.category" placeholder="请输入类别" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="queryItem">查询</el-button>
        <el-button type="default" @click="clear">清空</el-button>
      </el-form-item>
    </el-form>
  </div>

  <!-- 商品表格 -->
  <div>
    <el-table
      :data="tableData"
      style="width: 100%"
      row-key="id"
      border
      :tree-props="{ children: 'skuList', hasChildren: 'hasChildren' }"
    >
      <el-table-column fixed type="index" label="序号" align="center" width="80" />
      <el-table-column prop="code" label="商品编码" align="center" width="120" />
      <el-table-column prop="title" label="商品名称" align="center" width="120" />
      <el-table-column prop="categoryName" label="商品类别" align="center" width="120" />
      <el-table-column prop="description" label="商品描述" align="center" width="120" />
      <el-table-column prop="supplierName" label="供应商名称" align="center" width="120" />
      <el-table-column prop="brandName" label="品牌" align="center" width="120" />
      <el-table-column prop="code" label="商品条码" align="center" width="120" />
      <el-table-column prop="productWeight" label="商品重量" align="center" width="120" />
      <el-table-column prop="productLength" label="商品长度" align="center" width="120" />
      <el-table-column prop="productWidth" label="商品宽度" align="center" width="120" />
      <el-table-column prop="productHeight" label="商品高度" align="center" width="120" />
      <el-table-column prop="productVolume" label="商品体积" align="center" width="120" />
      <el-table-column prop="price" label="商品成本" align="center" width="120" />
      <el-table-column prop="realPrice" label="商品价格" align="center" width="120" />
      <el-table-column fixed="right" label="操作" align="center" width="120">
        <template #default="scope">
          <el-button size="small" @click="getItemById(scope.row.id)">
            编辑
          </el-button>
          <el-button size="small" @click="handleDelete(scope.row.id)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>

  <!-- 分页 -->
  <div>
    <el-pagination
      v-model:current-page="page"
      v-model:page-size="pageSize"
      :page-sizes="[5, 10, 15, 20]"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
  </div>

  <!-- 弹出框 -->
  <el-dialog v-model="dialogShow" :title="title" width="700" align-center>
    <el-form :model="dialogData" :rules="rules" ref="ruleFormRef" :label-width="formLabelWidth">
      <el-form-item label="商品编号" prop="code">
        <el-input v-model="dialogData.code" placeholder="请输入编号" />
      </el-form-item>
      <el-form-item label="商品名称" prop="title">
        <el-input v-model="dialogData.title" placeholder="请输入名称" />
      </el-form-item>
      <el-form-item label="商品类别">
        <el-cascader v-model="dialogData.categoryId" :options="categoryData" :props="props" placeholder="请选择类别" />
      </el-form-item>
      <el-form-item label="商品描述">
        <QuillEditor
          v-model:content="dialogData.description"
          contentType="text"
          theme="snow"
          style="height: 200px; width: 388px"
          placeholder="请输入商品描述..."
        />
      </el-form-item>
      <el-form-item label="供应商名称">
        <el-select v-model="dialogData.supplierId" placeholder="请选择">
          <el-option v-for="item in supplierData" :label="item.supplierName" :value="item.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="品牌" prop="brandId">
        <el-select v-model="dialogData.brandId" placeholder="请选择品牌">
          <el-option v-for="brand in brandOptions" :label="brand.label" :value="brand.value" />
        </el-select>
      </el-form-item>

      <!-- SKU 列表 -->
      <el-form-item>
        <el-button type="success" @click="addSkuList">
          <el-icon><CirclePlus /></el-icon>
        </el-button>
      </el-form-item>
      <el-scrollbar>
        <el-row :gutter="100" v-for="(item, index) in dialogData.skuList" :key="index" class="scrollbar-flex-content">
          <el-col :span="2">
            <el-form-item label="规格名称" style="width: 200px;">
              <el-input v-model="item.skutitle" placeholder="请输入" />
            </el-form-item>
          </el-col>
          <el-col :span="2">
            <el-form-item label="规格单位" style="width: 200px;">
              <el-input v-model="item.unit" placeholder="请输入" />
            </el-form-item>
          </el-col>
          <el-col :span="2">
            <el-form-item label="规格条码" style="width: 200px;">
              <el-input v-model="item.skucode" placeholder="请输入" />
            </el-form-item>
          </el-col>
          <el-col :span="2">
            <el-form-item label="商品重量" style="width: 200px;">
              <el-input v-model="item.productWeight" placeholder="请输入" />
            </el-form-item>
          </el-col>
          <el-col :span="2">
            <el-form-item label="商品长度" style="width: 200px;">
              <el-input v-model="item.productLength" placeholder="请输入" />
            </el-form-item>
          </el-col>
          <el-col :span="2">
            <el-form-item label="商品宽度" style="width: 200px;">
              <el-input v-model="item.productWidth" placeholder="请输入" />
            </el-form-item>
          </el-col>
          <el-col :span="2">
            <el-form-item label="商品高度" style="width: 200px;">
              <el-input v-model="item.productHeight" placeholder="请输入" />
            </el-form-item>
          </el-col>
          <el-col :span="2">
            <el-form-item label="商品体积" style="width: 200px;">
              <el-input v-model="item.productVolume" placeholder="请输入" />
            </el-form-item>
          </el-col>
          <el-col :span="2">
            <el-form-item label="商品成本" style="width: 200px;">
              <el-input v-model="item.price" placeholder="请输入" />
            </el-form-item>
          </el-col>
          <el-col :span="2">
            <el-form-item label="商品价格" style="width: 200px;">
              <el-input v-model="item.realPrice" placeholder="请输入" />
            </el-form-item>
          </el-col>
          <el-col :span="2">
            <el-button @click="deleteSkuList(index)">
              <el-icon><CloseBold /></el-icon>
            </el-button>
          </el-col>
        </el-row>
      </el-scrollbar>
    </el-form>
    <template #footer>
      <el-button @click="dialogShow = false" type="default">取消</el-button>
      <el-button type="primary" @click="saveItemInfo">确定</el-button>
    </template>
  </el-dialog>
</template>

<style scoped>
.scrollbar-flex-content {
  display: flex;
  flex-wrap: nowrap;
  width: fit-content;
}
.el-col {
  flex-shrink: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 50px;
  margin: 10px;
  text-align: center;
  border-radius: 4px;
}
</style>